package com.ywx.yypicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.ywx.yypicturebackend.config.CosClientConfig;
import com.ywx.yypicturebackend.constant.FileConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import com.ywx.yypicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * 与业务有关的公共文件处理方法
 */
@Slf4j
@Deprecated //已废弃，改为使用 upload 包的模板方法优化
public class FileManager {

    @Resource
    CosClientConfig cosClientConfig;

    @Resource
    CosManager cosManager;


    /**
     * 上传图片
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {

        //1.校验图片
        validPicture(multipartFile);

        //2.图片上传地址
        String uuid = RandomUtil.randomString(6);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
                uuid, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        //创建临时文件
        File file = null;

        try {
            file = File.createTempFile(uploadPath, null);
            //将文件内容拷贝到临时文件中
            multipartFile.transferTo(file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            //返回封装结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();

            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            //计算宽高比
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //3.删除临时文件
            this.deleteTempFile(file);
        }
    }


    /**
     * 通过URL上传图片
     *
     * @param fileUrl          图片URL
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPictureBuUrl(String fileUrl, String uploadPathPrefix) {

        //1.校验图片
        validPicture(fileUrl);

        //2.图片上传地址
        String uuid = RandomUtil.randomString(6);
        //String originalFilename = multipartFile.getOriginalFilename();
        String originalFilename = FileUtil.mainName(fileUrl);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),
                uuid, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        //创建临时文件
        File file = null;

        try {
            file = File.createTempFile(uploadPath, null);

            //下载文件
            HttpUtil.downloadFile(fileUrl, file);

            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            //返回封装结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();

            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            //计算宽高比
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            //3.删除临时文件
            this.deleteTempFile(file);
        }
    }


    /**
     * 校验文件
     *
     * @param multipartFile 前端上传的multipartFile文件
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);

        //校验图片的大小
        long fileSize = multipartFile.getSize();//单位为字节
        ThrowUtils.throwIf(fileSize > FileConstant.MAX_FILE_SIZE * FileConstant.ONE_M,
                ErrorCode.PARAMS_ERROR, String.format("文件大小不能超过%s%s", FileConstant.MAX_FILE_SIZE, "MB"));

        //校验图片后缀是否合法
        String originalFilename = multipartFile.getOriginalFilename();//获取文件原始名字
        ThrowUtils.throwIf(!FileConstant.ALLOW_FORMAT_LIST.contains(FileUtil.getSuffix(originalFilename)), ErrorCode.PARAMS_ERROR, "文件类型错误");


    }

    /**
     * 检验UrL图片,
     *
     * @param fileUrl
     */
    private void validPicture(String fileUrl) {
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        try {
            //1.验证URL格式
            new URL(fileUrl);//如果不是合法的URL则会报错
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }

        //2.校验URL协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCode.PARAMS_ERROR, "仅支持HTTP或HTTPS协议的文件地址");

        //3.发送HEAD请求验证是否存在,但要注意,不是所有图片URL都支持HEAD请求,所有请求失败不用直接抛出异常
        HttpResponse response = null;

        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();

            //如果没有正常响应,无需进行其他判断了,仅对能获取到的信息校验
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            //如果正常响应
            //4.检验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                boolean contains = FileConstant.ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase());
                ThrowUtils.throwIf(contains, ErrorCode.PARAMS_ERROR, "不支持该文件类型");
            }

            //5.检验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);

                    ThrowUtils.throwIf(contentLength > FileConstant.MAX_FILE_SIZE * FileConstant.ONE_M,
                            ErrorCode.PARAMS_ERROR, String.format("文件大小不能超过%s%s", FileConstant.MAX_FILE_SIZE, "MB"));
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }

            }

        } finally {
            //最终都要关闭响应
            if (response != null)
                response.close();
        }


    }

    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }


}
